<template>
  <div class="app-container">
    <el-link
      type="danger"
      :underline="false"
      class="mb20"
      v-if="mode == 'liuGe' && merchantId"
    >代下单商家:{{ merchantName }}</el-link>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-row class="out-border">
        <strong>商品类目</strong>
        <el-form-item label="服务类型" prop="categoryType">
          <el-tag
            size="large"
            style="margin-right: 10px; cursor: pointer"
            :type="
              ruleForm.categoryType != item.categoryType ? 'info' : 'success'
            "
            v-for="item in typesData"
            :key="item.categoryType"
            @click="(e) => onChange(item.categoryType, 'categoryType')"
          >{{ item.categoryName }}</el-tag>
        </el-form-item>
        <el-form-item label="服务类目" prop="categoryId" v-if="ruleForm.categoryType">
    
          <el-cascader
            v-model="ruleForm.categoryId"
            @input="(e) => onChange(e, 'categoryId')"
            placeholder="服务类目"
            :options="categoryData"
            :props="{
              label:'categoryName',
              value:'categoryId',
              children:'children'
            }"
            filterable
          ></el-cascader>
        </el-form-item>
      </el-row>
      <el-row class="out-border mt20">
        <strong>服务商品</strong>
        <el-form-item label="商品图片" prop="goodImage">
          <TheUpload
            ref="studyRefs"
            :files="ruleForm['goodImage']"
            :limit="5"
            @upload="
             (e)=>onChange(e,'goodImage')
            "
          />
        </el-form-item>
        <el-form-item label="商品类目" prop="serviceCategoryId" v-if="ruleForm.categoryId" style="display: none;">
          <el-select v-model="ruleForm.serviceCategoryId" placeholder="商品类目">
            <el-option
              v-for="item in serviceData"
              :key="item.serviceId"
              :label="item.serviceName"
              :value="item.serviceId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm.categoryType == 'INSTALLATION'" label="商品尺寸" prop="size">
          <el-input-number
            style="width: 400px"
            v-model="ruleForm.size"
            :min="1"
            :max="999999"
            :precision="2"
            :step="1"
            :controls="false"
          ></el-input-number>&nbsp;&nbsp;&nbsp;&nbsp;
          <span>{{ruleForm.serviceCategoryId&&serviceData.find(item=>item.serviceId==ruleForm.serviceCategoryId).serviceUnit}}</span>
        </el-form-item>
        <el-form-item label="商品备注" prop="goodRemark">
          <el-input type="textarea" v-model="ruleForm.goodRemark"></el-input>
        </el-form-item>
      </el-row>
      <el-row class="out-border mt20">
        <strong>客户信息</strong>
        <el-form-item label="客户姓名" prop="userName">
          <el-input v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
          <el-switch v-model="ruleForm.flag" inactive-text="虚拟号/分机号"></el-switch>
        </el-form-item>
        <el-form-item label="分机号" prop="flagPhone" v-if="ruleForm.flag">
          <el-input :maxlength="4" v-model="ruleForm.flagPhone"></el-input>
        </el-form-item>
        <el-form-item label="客户地址" prop="region">
          <el-cascader
            clearable
            :props="{ ...props }"
            v-model="ruleForm.region"
            style="width: 400px"
            placeholder="请选择"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <span @click="onChooseMap">
            <el-input :readonly="true" style="width: 400px" v-model="ruleForm.address"></el-input>
          </span>
          <ChooseMap ref="mapChooseRefs" :isDialog="true" @confirm="onMapConfirm" />
        </el-form-item>
        <el-form-item label="门牌号" prop="houseNum">
          <el-input v-model="ruleForm.houseNum"></el-input>
        </el-form-item>
        <el-form-item label="到货情况" prop="freightStatus">
          <el-radio-group v-model="ruleForm.freightStatus">
            <el-radio label="REACH">货物已到客户家</el-radio>
            <el-radio label="NOT_REACH">货物未到客户家</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="服务备注" prop="serviceRemark">
          <el-input type="textarea" v-model="ruleForm.serviceRemark"></el-input>
        </el-form-item>
        <el-form-item label="来源主订单号" prop="originOrderNumber">
          <el-input v-model="ruleForm.originOrderNumber"></el-input>
        </el-form-item>
      </el-row>
      <el-row class="out-line mt20 footBtn">
        <el-form-item>
          总计：
          <span v-loading="orderAmountLoading">{{ orderAmount | filterPriceFormat }}元</span>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-button type="primary" @click="submitForm('ruleForm')" style="margin-left: 20px">立即下单</el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <ThePay
      ref="payRefs"
      :dataId="merchantId"
      data-type="MERCHANT"
      @paySuccess="paySuccess"
      @payCancel="payCancel"
    />
  </div>
</template>

<script>
import TheUpload from "@/components/TheUpload";
import ThePay from "@/components/ThePay";
import {
  apiOrderBCreateOrder,
  apiServiceQuotationGetServiceQuotation,
  apiOrderBCreateOrderForAnother
} from "@/api/order.js";
import { apiServiceCategoryTree } from "@/api/serviceCategory.js";
import {
  apiServiceCategoryGetRootCategory,
  apiGetSysDistrictTreeWithServiceQuotation,
  apiGetServiceInfoByCategoryId
} from "@/api/serviceClassify";

import { apiCommonDistrict } from "@/api/worker.js";
import {
  validatePhone,
  validateRealName,
  validateIdNumber
} from "@/utils/validate";
import ChooseMap from "@/components/Map/chooseMap.vue";

export default {
  components: { TheUpload, ThePay, ChooseMap },
  data() {
    const _this = this;
    return {
      orderAmountLoading: false,
      orderAmount: 0,
      categoryData: [],
      serviceData: [],
      typesData: [],
      hilarityTime: "",
      ruleForm: {
        categoryType: "",
        categoryId: "",
        goodImage: [],
        goodRemark: "",
        userName: "",
        mobile: "",
        region: "",
        address: "",
        houseNum: "",
        addressLnt: "",
        addressLat: "",
        freightStatus: undefined,
        size: undefined,
        serviceRemark: "",
        serviceOrderId: ""
      },
      rules: {
        categoryType: [
          {
            required: true,
            message: "请选择服务类型",
            trigger: "change"
          }
        ],
        categoryId: [
          {
            required: true,
            message: "请选择服务类目",
            trigger: "change"
          }
        ],
        serviceCate: [
          { required: true, message: "请选择服务类型", trigger: "blur" }
        ],
        serviceCategoryId: [
          { required: true, message: "请选择商品类目", trigger: "blur" }
        ],
        goodImage: [
          {
            required: true,
            message: "请上传商品图片",
          },
          { type: "array", min: 1, message: "请上传商品图片", trigger: "change" }
        ],
        size: [
          {
            required: true,
            message: "请输入商品尺寸",
            trigger: "blur"
          },
          {
            type: "number",
            min: 1
          }
        ],

        userName: [
          { required: true, message: "请输入客户姓名", trigger: "blur" },
          { validator: validateRealName, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" }
        ],
        flagPhone: [
          {
            required: true,
            message: "请输入分机号",
            trigger: "blur"
          },
          { pattern: /[0-9]{4}/, message: "请输入4位分机号", trigger: "blur" }
        ],
        region: [
          { required: true, message: "请选择客户地址", trigger: "change" }
        ],
        address: [
          {
            required: true,
            message: "请输入详细地址",
            trigger: "change"
          }
        ],
        houseNum: [
          {
            required: true,
            message: "请输入门牌号",
            trigger: "change"
          }
        ],

        freightStatus: [
          {
            required: true,
            message: "请选择到货情况",
            trigger: "change"
          }
        ]
      },
      props: {
        lazy: true,
        value: "items",
        async lazyLoad(node, resolve) {
          let field = "";
          if (node.level > 0) {
            field = node.config.field;
          }
          const nodes = await _this.getDistrict(
            node.level > 0 ? node.value.id : 0,
            field
          );
          resolve(nodes);
        }
      },
      mode: "sass", //liuGe 平台代下单  sass 商家下单
      sassName: "",
      merchantId: ""
    };
  },
  watch: {
    "ruleForm.serviceCategoryId": {
      handler() {
        const { serviceCategoryId, region, categoryType, size } = this.ruleForm;
        if (serviceCategoryId && region && region.length > 0) {
          let params = {};
          if (categoryType == "INSTALLATION") {
            if (!size) return false;
            params = {
              serviceId: serviceCategoryId,
              provinceId: region[0].id,
              cityId: region[1].id,
              districtId: region[2].id,
              size:
                this.ruleForm.categoryType == "INSTALLATION"
                  ? this.ruleForm.size
                  : ""
            };
            this.orderAmountLoading = true;
            this.getServiceQuotation(params);
          } else {
            params = {
              serviceId: serviceCategoryId,
              provinceId: region[0].id,
              cityId: region[1].id,
              districtId: region[2].id
            };
            this.orderAmountLoading = true;
            this.getServiceQuotation(params);
          }
        }
      },
      deep: true
    },
    "ruleForm.size": {
      handler() {
        const { serviceCategoryId, region, categoryType, size } = this.ruleForm;
        if (serviceCategoryId && region && region.length > 0) {
          let params = {};
          if (categoryType == "INSTALLATION") {
            if (!size) return false;
            params = {
              serviceId: serviceCategoryId,
              provinceId: region[0].id,
              cityId: region[1].id,
              districtId: region[2].id,
              size:
                this.ruleForm.categoryType == "INSTALLATION"
                  ? this.ruleForm.size
                  : ""
            };
            this.orderAmountLoading = true;
            this.getServiceQuotation(params);
          } else {
            params = {
              serviceId: serviceCategoryId,
              provinceId: region[0].id,
              cityId: region[1].id,
              districtId: region[2].id
            };
            this.orderAmountLoading = true;
            this.getServiceQuotation(params);
          }
        }
      },
      deep: true
    },
    "ruleForm.region": {
      handler() {
        const { serviceCategoryId, region, categoryType, size } = this.ruleForm;
        if (serviceCategoryId && region && region.length > 0) {
          let params = {};
          if (categoryType == "INSTALLATION") {
            if (!size) return false;
            params = {
              serviceId: serviceCategoryId,
              provinceId: region[0].id,
              cityId: region[1].id,
              districtId: region[2].id,
              size:
                this.ruleForm.categoryType == "INSTALLATION"
                  ? this.ruleForm.size
                  : ""
            };
            this.orderAmountLoading = true;
            this.getServiceQuotation(params);
          } else {
            params = {
              serviceId: serviceCategoryId,
              provinceId: region[0].id,
              cityId: region[1].id,
              districtId: region[2].id
            };
            this.orderAmountLoading = true;
            this.getServiceQuotation(params);
          }
        }
      },
      deep: true
    }
  },
  mounted() {
    const { mode, merchantId, merchantName } = this.$route.query;
    this.mode = mode;
    this.merchantId = merchantId;
    this.merchantName = merchantName;

    this.getTypesData();
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const ruleForm = this.ruleForm;
          let params = {
            serviceType: ruleForm.categoryType,
            serviceId: ruleForm.serviceCategoryId,
            serviceCategoryId: ruleForm.categoryId[ruleForm.categoryId.length-1],
            remark: ruleForm.serviceRemark,
            province: ruleForm.region[0].name,
            city: ruleForm.region[1].name,
            district: ruleForm.region[2].name,
            provinceId: ruleForm.region[0].id,
            cityId: ruleForm.region[1].id,
            districtId: ruleForm.region[2].id,
            address: ruleForm.address + ruleForm.houseNum,
            addressLat: ruleForm.addressLat,
            addressLnt: ruleForm.addressLnt,
            userName: ruleForm.userName,
            userMobile: ruleForm.mobile,
            arrival: ruleForm.freightStatus,
            serviceRemark: ruleForm.serviceRemark,
            goodImages: ruleForm.goodImage.join(","),
            size:
              ruleForm.categoryType == "INSTALLATION" ? ruleForm.size : null,
            userVirtualNumber: ruleForm.flagPhone,
            userMobileType: ruleForm.flag ? "VIRTUAL_NUMBER" : "NORMAL",
            goodRemark: ruleForm.goodRemark,
            originOrderNumber: ruleForm.originOrderNumber
          };
          if (this.merchantId) {
            //代下单得商家id
            params.memberId = this.merchantId;
            console.log("下单参数：=》》》", params);
            apiOrderBCreateOrderForAnother(params).then(res => {
              const payUtils = {
                payWay: "BALANCE",
                payAmount: res.data.payAmount,
                mode: "order",
                ext: {
                  tradeType: "NATIVE",
                  serviceOrderId: res.data.serviceOrderId
                },
                hilarityTime: res.data.createTime
              };
              console.log(payUtils, "payUtils");

              this.$refs.payRefs.onShow(payUtils);
              // this.$message({
              //   type: "success",
              //   message: "下单成功",
              // });
            });
          } else {
            console.log("下单参数：=》》》", params);
            apiOrderBCreateOrder(params).then(res => {
              const payUtils = {
                payWay: "BALANCE",
                payAmount: res.data.payAmount,
                mode: "order",
                ext: {
                  tradeType: "NATIVE",
                  serviceOrderId: res.data.serviceOrderId
                },
                hilarityTime: res.data.createTime
              };
              console.log(payUtils, "payUtils");
              this.$refs.payRefs.onShow(payUtils);
              // this.$message({
              //   type: "success",
              //   message: "下单成功",
              // });
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    paySuccess() {
      this.$router.replace("/order/platform");
    },
    payCancel() {
      this.$router.replace("/order/platform");
    },
    onChooseMap() {
      this.$refs.mapChooseRefs.open();
    },
    onMapConfirm(info) {
      this.ruleForm.address = info.name+info.address;
      this.ruleForm.addressLat = info.lat;
      this.ruleForm.addressLnt = info.lng;
    },
    getDistrict(pid, field) {
      return new Promise((resolve, reject) => {
        apiCommonDistrict({ pid })
          .then(res => {
            resolve(
              res.data.map(item => {
                return {
                  value: item.id,
                  items: item,
                  label: item.name,
                  type: item.level,
                  leaf:
                    field && field === "common"
                      ? item.level == "area"
                      : item.level == "street"
                };
              })
            );
          })
          .catch(err => {
            reject([]);
          });
      });
    },
    onChange(e, field) {
      switch (field) {
        case "categoryType":
          // 获取服务
          if (this.ruleForm.categoryType == e) return;
          if (this.categoryData.length == 0) {
            this.getCategoryTree(e);
            this.ruleForm.categoryType = e;
            this.$refs.ruleForm.validateField(field);

            return false;
          } else {
            this.getCategoryTree(e[e.length - 1]);
            this.$refs.ruleForm.validateField(field);
          }

          this.$confirm("切换会导致数据清空，需要重新填写", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.$refs.ruleForm.clearValidate();
              this.ruleForm = {
                categoryType: e,
                categoryId: "",
                goodImage: [],
                serviceCategoryId: "",
                size: undefined,
                flag: false,
                flagPhone: "",
                goodRemark: "",
                userName: "",
                mobile: "",
                region: "",
                address: "",
                freightStatus: undefined,
                serviceRemark: "",
                originOrderNumber: ""
              };
            })
            .catch(() => {});
          break;
        case "categoryId":
          this.getServiceData(e);
          this.$refs.ruleForm.validateField(field);

          break;
        case "goodImage":
          this.ruleForm.goodImage = e.files.map(file => file.url);
          this.$refs.ruleForm.validateField(field);

          break;
        default:
          this.$refs.ruleForm.validateField(field);

          break;
      }
    },
    getTypesData() {
      apiServiceCategoryGetRootCategory({}).then(res => {
        this.typesData = res.data;
      });
    },
    getCategoryTree(categoryType) {
      apiServiceCategoryTree({
        serviceCategoryType: categoryType
      }).then(response => {
        this.categoryData = response.data;
      });
    },
    getServiceData(categoryId) {
      console.log(222);
      this.ruleForm = {
        ...this.ruleForm,
        serviceCategoryId: ""
      };

      apiGetServiceInfoByCategoryId({
        categoryId: categoryId[categoryId.length - 1]
      }).then(res => {
        this.serviceData = res.data;
        // 默认选中商品类目
        this.$nextTick(() => {
          this.ruleForm.serviceCategoryId = this.serviceData[0].serviceId;
        });
      });
    },
    guideCategory(data) {
      return data.filter(item => {
        if ("children" in item && item.children && item.children.length > 0) {
          return this.guideCategory(item.children);
        } else {
          return item;
        }
      });
    },
    getServiceQuotation(params) {
      return new Promise((resolve, reject) => {
        this.orderAmountLoading = true;
        apiServiceQuotationGetServiceQuotation(params)
          .then(res => {
            this.orderAmountLoading = false;
            this.$set(this, "orderAmount", res.data.serviceQuotationPrice);
            resolve(res.data.serviceQuotationPrice);
          })
          .catch(err => {
            this.orderAmountLoading = false;
            this.$set(this, "orderAmount", 0);

            resolve(0);
          });
      });
    }
  }
};
</script>

<style scoped lang="scss">
.input {
  width: 300px;
}
::v-deep .el-input__inner {
  width: 400px;
  text-align: left;
}
.footBtn {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
}
</style>
